/**
 * 
 */
package edu.umd.clip.lm.util;

import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;


public class DistributionBinding extends TupleBinding<Distribution> {
	public static final DistributionBinding instance = new  DistributionBinding();
	
	private DistributionBinding() {}
	/* (non-Javadoc)
	 * @see com.sleepycat.bind.tuple.TupleBinding#entryToObject(com.sleepycat.bind.tuple.TupleInput)
	 */
	@Override
	public Distribution entryToObject(TupleInput input) {
		long totalCount = input.readPackedLong();
		double backoff = input.readDouble();
		int numCounts = input.readPackedInt();
		Long2DoubleMap counts = new Long2DoubleMap(numCounts);
		for(int i=0; i<numCounts; ++i) {
			long k = input.readPackedLong();
			double v = input.readDouble();
			counts.put(k, v);
		}
		return new Distribution(counts, totalCount, backoff);
	}

	/* (non-Javadoc)
	 * @see com.sleepycat.bind.tuple.TupleBinding#objectToEntry(java.lang.Object, com.sleepycat.bind.tuple.TupleOutput)
	 */
	@Override
	public void objectToEntry(Distribution dist, TupleOutput output) {
		output.writePackedLong(dist.getTotalCount());
		output.writeDouble(dist.getBackoff());
		output.writePackedInt(dist.getDistribution().size());
		for(Long2DoubleMap.Iterator i = dist.getDistribution().iterator(); i.hasNext(); ) {
			Long2DoubleMap.Entry e = i.next();
			output.writePackedLong(e.getKey());
			output.writeDouble(e.getValue());
		}
	}
}